<template>
  <el-dialog :visible.sync="visible" v-dialogDrag :close-on-click-modal="false" class="tl-dialog" width="1000px" @open="open" @close="close">
    <template slot="title">
      <div style="margin: 5px">
        新增意见反馈<span class="text-button" @click="tabChange">去反馈广场看看有没有相似问题吧~</span>
      </div>
    </template>
    <div>
    </div>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit">
        <el-row>
          <div style="margin: 10px">
            <el-steps :active="0" finish-status="success" process-status="finish" align-center>
              <el-step title="提交反馈"></el-step>
              <el-step title="负责人分发"></el-step>
              <el-step title="办理人解决"></el-step>
              <el-step title="负责人确认"></el-step>
            </el-steps>
          </div>
        </el-row>
      <el-row>
        <div class="tl-form-line-title">
          请对问题进行描述
        </div>
        <el-col :span="24" label-width="0px">
          <el-form-item label="" prop="content" style="margin-left: -70px" :rules="rules.validateRequire">
            <el-input v-model="model.content" type="textarea" :rows="4" placeholder="提供详细的问题发生路径及截图，将会提升问题处理效率~" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <div class="tl-form-line-title">
          反馈相关
        </div>
				<el-col :span="12" v-if="bpaSystemFlag">
          <el-form-item label="所属业务" prop="belongbusiness" :rules="rules.validateRequire">
            <el-select v-model="model.belongbusiness" placeholder="请选择业务类型" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in codeModel.businessTypeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-else>
          <el-form-item label="业务类型"  prop="servicetype" :rules="rules.validateRequire"  >
            <el-select v-model="model.servicetype" placeholder="请选择业务类型" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in codeModel.feedbackServiceTypeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!bpaSystemFlag">
          <el-form-item label="所属系统" prop="system" :rules="rules.validateRequire" >
            <el-select v-model="model.system" placeholder="请先选择业务类型"  @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in feedbackSystemList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
      <!-- </el-row>
      <el-row> -->
        <el-col :span="12">
          <el-form-item label="反馈类型" prop="feedbacktype" :rules="rules.validateRequire">
            <el-select v-model="model.feedbacktype" @focus='filterItem' placeholder="请选择反馈类型" @change="changeDealPerson" filterable clearable>
              <el-option v-for="item in codeModel.feedbackTypeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属负责人" prop="systemresponsiblecode" :rules="rules.validateRequire">
            <el-input v-model="dispSystemResponsible" placeholder="请先选择反馈类型、业务类型和所属系统" :disabled="true"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发生时间" prop="faulttime"  v-if="isBugType">
            <el-date-picker v-model="model.faulttime" type="datetime" :picker-options="timePickerOptions" placeholder="请选择发生时间" value-format="yyyy-MM-dd HH:mm" format=" yyyy-MM-dd HH:mm"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="MmsSuggestionFeedback" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading">保存</el-button>
      <el-button type="primary" @click="doSubmitApproval" :loading="saveLoading" >提交</el-button>
      <el-button type="danger" @click="doDelete(model.id)" :disabled="!model.id" :loading="saveLoading" >删除</el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory"><svg-icon icon-class="list" />审批历史</el-button>
      <el-tooltip class="item" effect="light" content="保存后可上传附件" placement="right" :disabled="!disableAttachment">
        <tl-attachment source-type="MmsSuggestionFeedback" :source-id="model.id" :disabled="disableAttachment" :limit-type="limitType" :limit-count="4"></tl-attachment>
      </el-tooltip>
    </div>
  </el-dialog>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { MMS_FEEDBACK_TYPE } from '@/const/const'
import { MMS_SYSTEM_TYPE } from '@/const/const'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { },
  data() {
    return {
      moduleTitle: '意见反馈',
      urlPrefix: '/mms/suggestionFeedback/',
      url: {
        // 额外的url
        querySystemAndResponsible: '/mms/baseConfig/list',
        delete: '/mms/suggestionFeedback/delete'
      },
      systemInfo: [],
      limitType: "png,bmp,jpg,jpeg,gif,tiff,svg",
      isBugType: false,
      dispSystemResponsible: '',
      feedbackSystemList: [],
      timePickerOptions: {
        disabledDate: (date) => {
          return new Date(date).getTime() > new Date().getTime()
        }
      },
      qry_system: MMS_SYSTEM_TYPE.cdmc
    }
  },
	computed: {
    bpaSystemFlag() {
      return this.$store.getters.microGlobalParam.systemFlag === 'bpa'
		},
    /** 判断当前反馈所属系统是否为流程文档 */
    belongToBpa() {
      return this.model && this.model.system && this.model.system === MMS_SYSTEM_TYPE.cdmc
    }
	},
  methods: {
    /** 单个删除数据 */
    doDelete(id) {
      if (!this.url.delete) {
        this.$tap.alert('请设置delete地址!', 'warning')
        return
      }
      this.saveLoading = true
      this.$tap
        .confirm('确定删除数据吗？')
        .then((_) => {
          deleteAction(this.url.delete, { ids: id }).then((res) => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.visible = false
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.$emit("refresh")
            this.saveLoading = false
          })
        })
        .catch((_) => {
          this.saveLoading = false
        })
    },
    close() {
      this.model = {}
      this.isBugType = false
      this.dispSystemResponsible = ''
      this.$emit("refresh")
    },
    /** 重写提交方法，可以不用保存，直接提交 */
    doSubmitApproval() {
      if (!this.url.submit) {
        this.$tap.alert('请设置审批地址!', 'warning')
        return
      }
      let fileValidate = true
      this.$refs.form.validate((valid) => {
        if (!valid) {
          fileValidate = false
        }
      })
      if (!fileValidate) {
        return
      }
      this.saveLoading = true
      this.$tap
        .confirm('确定提交审批吗？提交后，单据内容不可修改！')
        .then((_) => {
          if (!this.beforeApproval()) {
            this.saveLoading = false
            return
          }
          if (this.isAdd) {
            // 增加唯一单号
            postAction(this.url.add + '?billuid=' + this.uid, this.model)
              .then((res) => {
                if (res.success) {
                  this.$tap.message('添加成功', 'success')
                  this.model = res.result
                  /** 提交审批 */
                  putAction(this.url.submit, this.model).then((res) => {
                    if (res.success) {
                      this.$tap.message(res.message, 'success')
                      this.queryData(this.model.id)
                      this.afterApproval()
                      this.visible = false
                    } else {
                      this.$tap.alert(res.message, 'warning')
                    }
                    this.$emit("refresh")
                    this.saveLoading = false
                  })
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.afterSubmit()
              })
              .catch((err) => {
                this.saveLoading = false
              })
          } else {
            if (!this.model.id) {
              this.saveLoading = false
              return
            }
            putAction(this.url.edit, this.model)
              .then((res) => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  /** 提交审批 */
                  putAction(this.url.submit, this.model).then((res) => {
                    if (res.success) {
                      this.$tap.message(res.message, 'success')
                      this.queryData(this.model.id)
                      this.afterApproval()
                      this.visible = false
                    } else {
                      this.$tap.alert(res.message, 'warning')
                    }
                    this.$emit("refresh")
                    this.saveLoading = false
                  })
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.afterSubmit()
              })
              .catch((err) => {
                this.saveLoading = false
              })
          }
        })
        .catch((_) => {
          this.saveLoading = false
          this.$emit("refresh")
        })
    },
    loaded() {
      // 页面加载完毕执行
      this.querySystemAndResponsible()
      this.assignDefaultValue()
      this.title = '新增' + this.moduleTitle
    },
    querySystemAndResponsible() {
      let qryParam = {}
      if (this.bpaSystemFlag) {
        // 当前页面由流程文档跳入
        qryParam.qry_system = MMS_SYSTEM_TYPE.cdmc
      }
      getAction(this.url.querySystemAndResponsible, qryParam)
        .then((res) => {
          if (res.success) {
            this.systemInfo = res.result.dataList
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterLoadData()
          this.loading = false
        })
        .catch((err) => {
          this.loading = false
        })
    },
    tabChange() {
      this.visible = false
      this.$parent.activeTab = 'allFeedback'
      this.$emit('changeTanNames')
    },
    /** 过滤反馈类型数据 */
    filterItem() {
      if (this.belongToBpa) {
        // 如果是流程文档，只保留流程建设和流程优化
        this.codeModel.feedbackTypeList = this.codeModel.feedbackTypeList.filter(item => item.code === MMS_FEEDBACK_TYPE.processOptimization || item.code === MMS_FEEDBACK_TYPE.processConstruction)
      } else {
        this.codeModel.feedbackTypeList = this.codeModel.feedbackTypeList.filter(item => item.code !== MMS_FEEDBACK_TYPE.processConstruction)
      }
    },
    changeDealPerson() {
      // 清空所属负责人
      this.$set(this.model, 'systemresponsiblecode', '')
      this.$set(this.model, 'systemresponsiblename', '')
      this.dispSystemResponsible = ''
      // 判断当前页面是否由流程文档跳入
      if (this.bpaSystemFlag) {
        // 选中所属业务才可遍历系统配置表
        if (this.model.belongbusiness && this.model.feedbacktype) {
          for (var i in this.systemInfo) {
             if (this.systemInfo[i].belongbusiness && this.systemInfo[i].belongbusiness === this.model.belongbusiness && this.systemInfo[i].feedbacktype.includes(this.model.feedbacktype)) {
              this.$set(this.model, 'systemresponsiblecode', this.systemInfo[i].systemresponsiblecode)
              this.$set(this.model, 'systemresponsiblename', this.systemInfo[i].systemresponsiblename)
              this.dispSystemResponsible = this.systemInfo[i].systemresponsiblename + '[' + this.systemInfo[i].systemresponsiblecode + ']'
            }
          }
        }
      } else {
         this.dispSystemResponsible = ''
        // 只有已配置系统的业务类型，所属系统才有值
        this.feedbackSystemList = []
        if (this.model.servicetype) {
          this.systemInfo.forEach(item => {
            if (item.servicetype && item.servicetype.includes(this.model.servicetype)) {
              this.codeModel.feedbackSystemList.forEach(systemItem => {
                if (!this.feedbackSystemList.includes(systemItem) && systemItem.code === item.system) {
                  this.feedbackSystemList.push(systemItem)
                }
              })
            }
          })
          if (this.feedbackSystemList.length === 0) {
            this.$set(this.model, 'system', '')
          }
        }
        // 所属负责人
        if (this.model.feedbacktype && this.model.servicetype && this.model.system) {
          this.systemInfo.forEach(item => {
            if (item.feedbacktype.includes(this.model.feedbacktype) && item.servicetype.includes(this.model.servicetype) && item.system.includes(this.model.system)) {
              this.$set(this.model, 'systemresponsiblecode', item.systemresponsiblecode)
              this.$set(this.model, 'systemresponsiblename', item.systemresponsiblename)
              this.dispSystemResponsible = item.systemresponsiblename + '[' + item.systemresponsiblecode + ']'
            }
          })
        }
      }
      // BUG类型需要填写错误发生时间
      if (this.model.feedbacktype === '1') {
        this.isBugType = true
      } else {
        this.isBugType = false
        this.$set(this.model, 'faulttime', '')
      }
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'submitperson', this.$store.getters.user.code)
        this.$set(this.model, 'submitpersonname', this.$store.getters.user.name)
        this.$set(this.model, 'applyusercode', this.$store.getters.user.code)
        this.$set(this.model, 'applyusername', this.$store.getters.user.name)
        this.$set(this.model, 'usercode', this.$store.getters.user.code)
        this.$set(this.model, 'username', this.$store.getters.user.name)
        this.$set(this.model, 'deptcode', this.$store.getters.dept.code)
        this.$set(this.model, 'deptname', this.$store.getters.dept.name)
        // 当从流程文档跳入当前页面，设置所属系统默认值为流程文档
        if (this.bpaSystemFlag) {
          this.$set(this.model, 'system', MMS_SYSTEM_TYPE.cdmc)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.text-button {
  float: right;
  font-family: '苹方-简 中等', '苹方-简', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  //color: #909399;
  height: 15px;
  margin: 8px 50px 10px 8px;
  line-height: 15px;
  vertical-align: middle;
  color: #0A6ED2;
  &:hover {
   cursor: pointer;
 }
}
</style>

